package com.sjht.android.bxgz.network;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.zip.GZIPInputStream;

import org.apache.http.Header;
import org.apache.http.HeaderElement;
import org.apache.http.HttpEntity;
import org.apache.http.HttpException;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.HttpRequestInterceptor;
import org.apache.http.HttpResponse;
import org.apache.http.HttpResponseInterceptor;
import org.apache.http.HttpStatus;
import org.apache.http.HttpVersion;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.client.params.HttpClientParams;
import org.apache.http.client.utils.URIUtils;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.conn.params.ConnPerRouteBean;
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.conn.routing.HttpRoute;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.HttpEntityWrapper;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HttpContext;

import android.util.Log;

import com.sjht.android.bxgz.utils.StringUtils;

public class AsyncHttpClient extends IAsyncRequest {

	/** 最大连接数 */
	private static final int MAX_TOTAL_CONNECTION = 100;
	/** 每个路由最大连接数 */
	private final static int MAX_ROUTE_CONNECTIONS = 20;

	/** 连接池获取连接的最大等待时间 */
	private final static int DEFAULT_WAIT_TIMEOUT = 10000;
	/** 设置连接超时时间 */
	private static final int DEFAULT_CONN_TIMEOUT = 10000;
	/** socket读取数据超时时间 */
	private static final int DEFAULT_READ_TIMEOUT = 20000;

	private static DefaultHttpClient mHttpClient;
	private static ThreadSafeClientConnManager mConnManager;

	private HttpRequestBase mHttpRequest;
	private HttpResponse mHttpResponse;

	private InputStream mInputStream;
	private BufferedReader mReader;

	private RequestEntity mRequestEntity;

	static {
		// Create and initialize HTTP parameters
		HttpParams params = new BasicHttpParams();
		HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
		// 设置最大连接数
		ConnManagerParams.setMaxTotalConnections(params, MAX_TOTAL_CONNECTION);
		// 设置每个路由最大连接数
		ConnPerRouteBean connPerRouteBean = new ConnPerRouteBean(MAX_ROUTE_CONNECTIONS);
		// 对localhost:80增加最大连接到50
		HttpHost localhost = new HttpHost("locahost", 80);
		connPerRouteBean.setMaxForRoute(new HttpRoute(localhost), 50);
		ConnManagerParams.setMaxConnectionsPerRoute(params, new ConnPerRouteBean(MAX_ROUTE_CONNECTIONS));
		// 设置从连接池获取连接的最大等待时间
		ConnManagerParams.setTimeout(params, DEFAULT_WAIT_TIMEOUT);
		// 设置连接超时时间
		HttpConnectionParams.setConnectionTimeout(params, DEFAULT_CONN_TIMEOUT);
		// 设置socket读取数据超时时间
		HttpConnectionParams.setSoTimeout(params, DEFAULT_READ_TIMEOUT);
		// 设置以Socket 缓存大小
		HttpConnectionParams.setSocketBufferSize(params, 8192);
		// 设置重定向，缺省为 true , 这里设置成不重定向
		HttpClientParams.setRedirecting(params, false);

		// Create and initialize scheme registry
		SchemeRegistry schemeRegistry = new SchemeRegistry();
		schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
		schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));

		// Create an HttpClient with the ThreadSafeClientConnManager.
		// This connection manager must be used if more than one thread will
		// be using the HttpClient.
		mConnManager = new ThreadSafeClientConnManager(params, schemeRegistry);
		mHttpClient = new DefaultHttpClient(mConnManager, params);

		mHttpClient.addRequestInterceptor(new HttpRequestInterceptor() {
			public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException {
				if (!request.containsHeader(HttpHeader.REQ.ACCEPT_ENCODING)) {
					request.addHeader(HttpHeader.REQ.ACCEPT_ENCODING, "gzip");
				}
			}
		});

		mHttpClient.addResponseInterceptor(new HttpResponseInterceptor() {
			public void process(final HttpResponse response, final HttpContext context) throws HttpException,
					IOException {
				HttpEntity entity = response.getEntity();
				Header ceheader = entity.getContentEncoding();
				if (ceheader != null) {
					HeaderElement[] codecs = ceheader.getElements();
					for (int i = 0; i < codecs.length; i++) {
						if (codecs[i].getName().equalsIgnoreCase("gzip")) {
							response.setEntity(new GzipDecompressingEntity(response.getEntity()));
							return;
						}
					}
				}
			}
		});
	}

	@Override
	public InputStream execute(RequestEntity requestEntity) throws Exception {
		mRequestEntity = requestEntity;
		if (mRequestEntity == null)
			return null;
		// 网络探测
		Apn.init();

		// 设置代理
		if (Apn.M_USE_PROXY) {
			HttpHost proxy = new HttpHost(Apn.M_APN_PROXY, Apn.M_APN_PORT);
			mHttpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
		} else {
			mHttpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, null);
		}

		// 判断是什么方式请求
		if (mRequestEntity.getMethod() == RequestEntity.METHOD_GET) {
			URI uri = URIUtils.createURI(HTTP_SCHEME, HTTP_HOST, -1, HTTP_AGENT,
					URLEncodedUtils.format(fillGetParams(), "UTF-8"), null);
			Log.e("url", uri.toString());
			mHttpRequest = new HttpGet(uri);
		} else {
			URI uri = URIUtils.createURI(HTTP_SCHEME, HTTP_HOST, -1, HTTP_AGENT, null, null);
			Log.e("url", uri.toString());
			HttpPost httpPost = new HttpPost(uri);
			httpPost.setEntity(fillPostParams());
			mHttpRequest = httpPost;
		}

		// 填充 HTTP 头
		fillHeader();

		mHttpResponse = mHttpClient.execute(mHttpRequest);

		switch (mHttpResponse.getStatusLine().getStatusCode()) {
		case HttpStatus.SC_OK:
			// 抄录 inputstream, gzip 支持
			HttpEntity entity = mHttpResponse.getEntity();

			if (entity != null) {
				mInputStream = entity.getContent();
			}
			return mInputStream;
		}
		return null;
	}

	public InputStream execute(String url) throws Exception {
		// 网络探测
		Apn.init();

		// 设置代理
		if (Apn.M_USE_PROXY) {
			HttpHost proxy = new HttpHost(Apn.M_APN_PROXY, Apn.M_APN_PORT);
			mHttpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
		} else {
			mHttpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, null);
		}

		// 判断是什么方式请求
		mHttpRequest = new HttpGet(url);

		// 填充 HTTP 头
		fillHeader();

		mHttpResponse = mHttpClient.execute(mHttpRequest);

		switch (mHttpResponse.getStatusLine().getStatusCode()) {
		case HttpStatus.SC_OK:
			// 抄录 inputstream, gzip 支持
			HttpEntity entity = mHttpResponse.getEntity();
			if (entity != null) {
				mInputStream = entity.getContent();
			}
			return mInputStream;
		}
		return null;
	}

	public String execute(String messageName, String paramStr) throws ClientProtocolException, IOException {
		// 网络探测
		Apn.init();
		StringBuffer sb = new StringBuffer();
		// 设置代理
		if (Apn.M_USE_PROXY) {
			HttpHost proxy = new HttpHost(Apn.M_APN_PROXY, Apn.M_APN_PORT);
			mHttpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
		} else {
			mHttpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, null);
		}
		String url = HTTP_SCHEME + "://" + HTTP_HOST + HTTP_AGENT + "/" + messageName + "/" + paramStr;
		if(paramStr == null)
			url = HTTP_SCHEME + "://" + HTTP_HOST + HTTP_AGENT + "/" + messageName;
		Log.e("url", url);
		// 判断是什么方式请求
		mHttpRequest = new HttpGet(url);

		// 填充 HTTP 头
		fillHeader();

		mHttpResponse = mHttpClient.execute(mHttpRequest);

		switch (mHttpResponse.getStatusLine().getStatusCode()) {
		case HttpStatus.SC_OK:
			// 抄录 inputstream, gzip 支持
			HttpEntity entity = mHttpResponse.getEntity();
			if (entity != null) {
				mInputStream = entity.getContent();
				mReader = new BufferedReader(new InputStreamReader(mInputStream));
				String s = null;
				if (mReader != null) {
					s = mReader.readLine();
					while (s != null) {
						sb.append(s);
						s = mReader.readLine();
					}
				}
			}
			return sb.toString();
		}
		return null;
	}

	public String post(String messageName, Map<String, String> map) throws ClientProtocolException, IOException {
		// 网络探测
		Apn.init();
		StringBuffer sb = new StringBuffer();
		// 设置代理
		if (Apn.M_USE_PROXY) {
			HttpHost proxy = new HttpHost(Apn.M_APN_PROXY, Apn.M_APN_PORT);
			mHttpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
		} else {
			mHttpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, null);
		}
		String url = HTTP_SCHEME + "://" + HTTP_HOST + HTTP_AGENT + "/" + messageName;
		Log.e("url", url);
		// 判断是什么方式请求
		HttpPost httpPost = new HttpPost(url);
		httpPost.setEntity(fillPostParams(map));

		Map<String, String> headers = new HashMap<String, String>();
		headers.put(
				HttpHeader.REQ.ACCEPT,
				"application/vnd.wap.xhtml+xml,application/xml,text/vnd.wap.wml,text/html,application/xhtml+xml,image/jpeg;q=0.5,image/png;q=0.5,image/gif;q=0.5,image/*;q=0.6,video/*,audio/*,*/*;q=0.6");
		headers.put(HttpHeader.REQ.CONTENT_TYPE, "application/json; charset=utf-8");

		// 填充 HTTP 头
		fillHeader(httpPost, headers);

		
		mHttpResponse = mHttpClient.execute(httpPost);

		switch (mHttpResponse.getStatusLine().getStatusCode()) {
		case HttpStatus.SC_OK:
			// 抄录 inputstream, gzip 支持
			HttpEntity entity = mHttpResponse.getEntity();
			if (entity != null) {
				mInputStream = entity.getContent();
				mReader = new BufferedReader(new InputStreamReader(mInputStream));
				String s = null;
				if (mReader != null) {
					s = mReader.readLine();
					while (s != null) {
						sb.append(s);
						s = mReader.readLine();
					}
				}
			}
			return sb.toString();
		}
		return null;
	}

	public String upload(String messageName, String params) {
		StringBuilder sb = new StringBuilder();
		try {
			URL url = new URL(HTTP_SCHEME + "://" + HTTP_HOST + HTTP_AGENT + "/" + messageName);
			HttpURLConnection connection = openConnection(url, true, true, "POST");
			BufferedOutputStream out = new BufferedOutputStream(connection.getOutputStream());
			out.write(params.getBytes());
			out.flush();
			out.close();
			// 读取URLConnection的响应
			BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
			StringBuffer strBuffer = new StringBuffer();
			String result = null;
			while ((result = br.readLine()) != null) {
				sb.append(result);
			}
			result = strBuffer.toString();
			strBuffer.delete(0, strBuffer.length());
			if (br != null)
				br.close();
			connection = null;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return sb.toString();
	}

	public static final HttpURLConnection openConnection(URL url, boolean in, boolean out,String requestMethode) throws IOException{
        HttpURLConnection con = (HttpURLConnection) url.openConnection ();
        con.setDoInput(in);
        con.setDoOutput (out);
        if(requestMethode == null){
            requestMethode = "GET";
        }
        con.setRequestMethod(requestMethode);
        con.setRequestProperty ("Content-Type", "application/json; charset=utf-8");
        con.addRequestProperty("connection", "keep-alive");
        con.addRequestProperty("Charsert", "UTF-8");
        return con;
    }
	
	public String upload(String messageName, Map<String, String> map) {
		StringBuilder sb = new StringBuilder();
		try {
			URL url = new URL(HTTP_SCHEME + "://" + HTTP_HOST + HTTP_AGENT + "/" + messageName);
			HttpURLConnection connection = openConnection(url, true, true, "POST");
			// connection.setDoInput(true);
			// connection.setDoOutput(true);
//			connection.setRequestMethod();
//			connection.setRequestProperty("connection", "keep-alive");
//			connection.setRequestProperty("Charsert", "UTF-8");
//			connection.setRequestProperty("Content-Type", "application/json; charset=utf-8");
			for (Map.Entry<String, String> entry : map.entrySet()) {
				if (!StringUtils.isNullOrEmpty(entry.getValue()))
					connection.addRequestProperty(entry.getKey(), entry.getValue());
			}
			// 读取URLConnection的响应
			BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
			String result = null;
			while ((result = br.readLine()) != null) {
				sb.append(result);
			}
			if (br != null)
				br.close();
			connection = null;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return sb.toString();
	}

	private UrlEncodedFormEntity fillPostParams(Map<String, String> map) throws IOException {
		List<NameValuePair> formparams = new ArrayList<NameValuePair>();
		for (Map.Entry<String, String> entry : map.entrySet()) {
			if (!StringUtils.isNullOrEmpty(entry.getValue()))
				formparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
		}
		return new UrlEncodedFormEntity(formparams, "UTF-8");
	}

	private List<NameValuePair> fillGetParams() {
		List<NameValuePair> qparams = new ArrayList<NameValuePair>();
		Map<String, String> params = mRequestEntity.getParams();
		for (Map.Entry<String, String> entry : params.entrySet()) {
			if (!StringUtils.isNullOrEmpty(entry.getValue()))
				qparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
		}
		return qparams;
	}

	private UrlEncodedFormEntity fillPostParams() throws IOException {
		List<NameValuePair> formparams = new ArrayList<NameValuePair>();
		Map<String, String> params = mRequestEntity.getParams();
		for (Map.Entry<String, String> entry : params.entrySet()) {
			if (!StringUtils.isNullOrEmpty(entry.getValue()))
				formparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
		}
		return new UrlEncodedFormEntity(formparams, "UTF-8");
	}

	private void fillHeader() {
		if (mRequestEntity != null) {
			Map<String, String> headerMap = mRequestEntity.getHeaders();
			for (Map.Entry<String, String> entry : headerMap.entrySet()) {
				mHttpRequest.setHeader(entry.getKey(), entry.getValue());
			}
		}
	}

	private void fillHeader(HttpPost post, Map<String, String> map) {
		for (Map.Entry<String, String> entry : map.entrySet()) {
			post.setHeader(entry.getKey(), entry.getValue());
		}
	}

	public static void shutdown() {
		mHttpClient.getConnectionManager().shutdown();
	}

	@Override
	public void close() {
		if (mReader != null) {
			try {
				mReader.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		if (mInputStream != null) {
			try {
				mInputStream.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		abort();
		// 关闭过期连接
		mConnManager.closeExpiredConnections();
		// 可选地，关闭空闲超过30秒的连接
		mConnManager.closeIdleConnections(30, TimeUnit.SECONDS);
	}

	@Override
	public void abort() {
		if (mHttpRequest != null)
			mHttpRequest.abort();
	}

	/**
	 * @return
	 */
	public static HttpClient getHttpClient() {
		return mHttpClient;
	}

	static class GzipDecompressingEntity extends HttpEntityWrapper {
		public GzipDecompressingEntity(final HttpEntity entity) {
			super(entity);
		}

		@Override
		public InputStream getContent() throws IOException, IllegalStateException {
			// the wrapped entity's getContent() decides about repeatability
			InputStream wrappedin = wrappedEntity.getContent();
			return new GZIPInputStream(wrappedin);
		}

		@Override
		public long getContentLength() {
			// length of ungzipped content is not known
			return -1;
		}
	}

}
